<template>
  <el-radio-group v-model="selectValue" :clearable="clearable" :disabled="disabled" :readonly="readonly" @change="onChange">
    <el-radio v-for="item in list" :key="item.dictValue" :label="item.dictValue"> {{ item.dictLabel }} </el-radio>
  </el-radio-group>
</template>
<script>
import { postRequest, getLocalStorage } from "@/api/mains";

export default defineComponent({
  name: "CommonRadio",
  props: {
    modelValue: {
      type: [Number, String],
      default: ""
    },
    opitionList: {
      type: Array,
      default: () => []
    },
    dictUrl: {
      type: String,
      default: ""
    },
    clearable: {
      type: Boolean,
      default: true
    },
    dictCode: {
      type: String,
      default: ""
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  emits: {
    "update:model-value": null,
    change: null
  },

  setup(props, { emit }) {
    const selectValue = ref(props.modelValue);
    const list = ref([]);

    const getList = async () => {
      const { dictUrl, dictCode } = props;

      //  若传入url则按通过url获取数据
      if (dictUrl) {
        const { datas } = await postRequest(dictUrl);
        list.value = datas;
      } else if (dictCode) {
        list.value = getLocalStorage()[dictCode];
      }
    };

    getList();

    const onChange = value => {
      emit("update:model-value", value);
      emit("change", value);
    };

    watch(
      () => props.opitionList,
      newVal => {
        if (newVal && newVal.length) {
          list.value = newVal;
        }
      },
      {
        deep: true,
        immediate: true
      }
    );

    watch(
      () => props.modelValue,
      newVal => {
        if (newVal != selectValue.value) {
          selectValue.value = newVal;
        }
      }
    );

    watch(
      () => props.dictCode,
      newVal => {
        if (newVal) {
          list.value = getLocalStorage()[newVal];
        }
      }
    );

    return {
      selectValue,
      list,
      onChange
    };
  }
});
</script>
